from sqlalchemy import Column, Integer, String, CHAR
from sqlalchemy.dialects.mysql import LONGTEXT
from datetime import datetime
from models.base import Base, db


class Orders(Base):
    __tablename__ = 'orders'
    id = Column(Integer, primary_key=True, autoincrement=True)
    order_number = Column(String(30), nullable=False, unique=True)
    title = Column(String(100), nullable=False)
    author = Column(String(20), default='佚名')
    content = Column(LONGTEXT, default='佚名')
    char_sum = Column(Integer, default=0)
    create_time = Column('create_time', Integer)
    status = Column(CHAR, default='0')

    def __init__(self):
        self.create_time = int(datetime.now().timestamp())

    @classmethod
    def is_unique(cls, order_number):
        order = db.query(cls).filter_by(order_number=order_number).first()
        if order:
            return False
        else:
            return True

    def get_status(cls, order_number):
        order_status = db.query(cls).filter_by(order_number=order_number).first()
        if order_status:
            return order_status.status
        else:
            return False

    @property
    def create_datetime(self):
        if self.create_time:
            return datetime.utcfromtimestamp(self.create_time + 28800).strftime("%Y-%m-%d %H:%M:%S")
        else:
            return None

    def search_order(cls, order_number):
        info = db.query(cls).filter_by(order_number=order_number).first()
        return info if info else False

    def update_status(self, order_number):
        # user_result = session.query(User).filter_by(id='1').first()
        sql = "update orders set status = '1' where order_number = %s" % order_number
        db.execute(sql)
